package org.bedracket.pgeg.network;

import io.netty.buffer.Unpooled;
import net.minecraft.client.KeyMapping;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.NetworkHooks;
import org.bedracket.pgeg.init.EModKeyMappings;
import org.bedracket.pgeg.screen.TestMenu;
import org.jetbrains.annotations.Nullable;

import java.util.function.Supplier;

public class OpenTestMenuMessage {

    public static final KeyMapping OPEN_TEST_MENU =
            EModKeyMappings.OPEN_TEST_MENU.getKeyMapping();

    public OpenTestMenuMessage() {

    }

    public OpenTestMenuMessage(FriendlyByteBuf buf) {
    }

    public static void buffer(OpenTestMenuMessage message, FriendlyByteBuf buf) {

    }

    public static void handler(OpenTestMenuMessage message, Supplier<NetworkEvent.Context> context) {
        context.get().enqueueWork(() -> {
            ServerPlayer player = context.get().getSender();
            if (player != null) {
                pressButton(player);
            }
        });
        context.get().setPacketHandled(true);
    }

    public static void pressButton(Player player) {
        var pos = player.getOnPos();
        var level = player.getLevel();
        if (!level.isAreaLoaded(pos, 1)) {
            return;
        }
        if (OPEN_TEST_MENU.isDown()) {
            if (player instanceof final ServerPlayer serverPlayer && !(player instanceof FakePlayer)) {
                NetworkHooks.openScreen(serverPlayer, new MenuProvider() {

                    @Override
                    public Component getDisplayName() {
                        return Component.translatable("test");
                    }

                    @Nullable
                    @Override
                    public AbstractContainerMenu createMenu(int pContainerId, Inventory pPlayerInventory, Player pPlayer) {
                        return new TestMenu(pContainerId, pPlayerInventory, new FriendlyByteBuf(Unpooled.buffer()).writeBlockPos(pos));
                    }
                }, pos);
            }
        }
    }
}
